<?php

include_once './I18N.php';


class Distance {

    /**
     * Computes the distance between the 2 users in kilometers;
     * If any of the both users doesn't have set his location, then -1 is returned.
     *
     * @param User $user1
     * @param User $user2
     * @return -1 if distance is unknown
     */
    public static function computeDistance($user1, $user2) {
        if (!isset($user1) || !isset($user2)
                || !isset($user1->fb_location) || !isset($user2->fb_location)
                || !isset($user1->fb_location->lon) || !isset($user1->fb_location->lat)
                || $user1->fb_location->lon=='' || $user1->fb_location->lat==''
                || !isset($user2->fb_location->lon) || !isset($user2->fb_location->lat)
                || $user2->fb_location->lon=='' || $user2->fb_location->lat=='') {
            return -1;  // unkown
        }

        $lon1 = $user1->fb_location->lon;
        $lat1 = $user1->fb_location->lat;
        $lon2 = $user2->fb_location->lon;
        $lat2 = $user2->fb_location->lat;

        $pi80 = M_PI / 180;
        $lat1 *= $pi80;
        $lon1 *= $pi80;
        $lat2 *= $pi80;
        $lon2 *= $pi80;
        $r = 6372.797; // mean radius of Earth in km
        $dlat = $lat2 - $lat1;
        $dlon = $lon2 - $lon1;
        $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlon / 2) * sin($dlon / 2);
        $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
        $km = $r * $c;

        return $km;
    }

    /**
     * Returns an associative array with distance informations: value and units.
     * If any of the users doesn't have specified his location, then both fields are set to null;
     *
     * @param object $user1
     * @param object $user2
     * @return
     */
    public static function getDistanceArray($user1, $user2) {
        $returnArray = array();
        $km  = self::computeDistance($user1, $user2);

        if ($km == -1) {
            $returnArray['value'] = NULL;
            $returnArray['units'] = NULL;
        }
        else if ($km > 10) {
            $returnArray['value'] = sprintf("%d", $km);
            $returnArray['units'] = I18N::getMessage('distance.km');
        }
        else if ($km > 1) {
            $returnArray['value'] = sprintf("%.1f", $km);
            $returnArray['units'] = I18N::getMessage('distance.km');
        }
        else {
            $returnArray['value'] = sprintf("%d", $km * 1000);
            $returnArray['units'] = I18N::getMessage('distance.m');
        }

        return $returnArray;
    }
}

?>
